package com.qdc.datacenters.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.qdc.datacenters.client.CorpCustomerClient;
import com.qdc.datacenters.domain.entity.ChatMsgGroupStatistic;
import com.qdc.datacenters.domain.query.chatmsg.ChatMsgListQuery;
import com.qdc.datacenters.domain.query.qw.QwGroupChatStatisticQuery;
import com.qdc.datacenters.domain.vo.chatmsg.ChatMsgRoomListVo;
import com.qdc.datacenters.domain.vo.qw.QwGroupChatStatisticVo;
import com.qdc.datacenters.service.IChatMsgGroupStatisticService;
import com.qdc.datacenters.service.ICorpGroupService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 群聊统计任务
 *
 * @author danmo
 * @date 2024-03-25 11:03
 **/
@Slf4j
@Component
public class GroupChatStatisticTask {

    @Autowired
    private ICorpGroupService iCorpGroupService;

    @Resource
    private CorpCustomerClient corpCustomerClient;

    @Autowired
    private IChatMsgGroupStatisticService groupStatisticService;

    @Async
    @Scheduled(cron = "0 0 5 * * ?")
    public void handler() {
        log.info("开始拉取【群聊数据统计】数据");
        ChatMsgListQuery msgListQuery = new ChatMsgListQuery();
        msgListQuery.setGroupType(1);
        List<ChatMsgRoomListVo> roomMsgList = iCorpGroupService.getRoomMsgList(msgListQuery);
        if (CollectionUtil.isNotEmpty(roomMsgList)) {
            List<String> ownerList = roomMsgList.stream().map(ChatMsgRoomListVo::getOwner).distinct().collect(Collectors.toList());
            List<List<String>> partitionList = ListUtil.partition(ownerList, 100);
            List<ChatMsgGroupStatistic> weGroupStatisticList = new ArrayList<>();
            for (List<String> owners : partitionList) {
                QwGroupChatStatisticQuery query = new QwGroupChatStatisticQuery();
                //前一天的数据
                Long startTime = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)).getTime() / 1000;
                Long endTime = DateUtil.endOfDay(DateUtil.offsetDay(new Date(), -1)).getTime() / 1000;
                query.setDay_begin_time(startTime);
                query.setDay_end_time(endTime);
                QwGroupChatStatisticQuery.OwnerFilter ownerFilter = new QwGroupChatStatisticQuery.OwnerFilter();
                ownerFilter.setUserid_list(owners);
                query.setOwnerFilter(ownerFilter);
                try {
                    QwGroupChatStatisticVo groupChatStatistic = corpCustomerClient.getGroupChatStatisticGroupByDay(query);
                    if (groupChatStatistic != null && CollectionUtil.isNotEmpty(groupChatStatistic.getItems())) {
                        List<QwGroupChatStatisticVo.GroupchatStatisticData> items = groupChatStatistic.getItems();
                        items.forEach(groupchatStatisticData -> {
                            ChatMsgGroupStatistic groupStatistic = new ChatMsgGroupStatistic();
                            QwGroupChatStatisticVo.StatisticData data = groupchatStatisticData.getData();
                            BeanUtils.copyProperties(data, groupStatistic);
                            groupStatistic.setStatTime(groupchatStatisticData.getStatTime());
                            weGroupStatisticList.add(groupStatistic);
                        });
                    }

                } catch (Exception e) {
                    log.error("群聊数据拉取失败: query:{}", JSONObject.toJSONString(query), e);
                }
            }
            if (CollectionUtil.isNotEmpty(weGroupStatisticList)) {
                Map<Date, List<ChatMsgGroupStatistic>> dateListMap = weGroupStatisticList.stream().collect(Collectors.groupingBy(ChatMsgGroupStatistic::getStatTime));
                List<ChatMsgGroupStatistic> resList = new ArrayList<>();
                dateListMap.forEach((sendTime, statisticList) -> {
                    ChatMsgGroupStatistic statistic = new ChatMsgGroupStatistic();
                    statistic.setChatTotal(statisticList.stream().mapToInt(ChatMsgGroupStatistic::getChatTotal).sum());
                    statistic.setChatHasMsg(statisticList.stream().mapToInt(ChatMsgGroupStatistic::getChatHasMsg).sum());
                    statistic.setNewChatCnt(statisticList.stream().mapToInt(ChatMsgGroupStatistic::getNewChatCnt).sum());
                    statistic.setNewMemberCnt(statisticList.stream().mapToInt(ChatMsgGroupStatistic::getNewMemberCnt).sum());
                    statistic.setMemberTotal(statisticList.stream().mapToInt(ChatMsgGroupStatistic::getMemberTotal).sum());
                    statistic.setNewChatCnt(statisticList.stream().mapToInt(ChatMsgGroupStatistic::getNewMemberCnt).sum());
                    statistic.setMemberHasMsg(statisticList.stream().mapToInt(ChatMsgGroupStatistic::getMemberHasMsg).sum());
                    statistic.setMsgTotal(statisticList.stream().mapToInt(ChatMsgGroupStatistic::getMsgTotal).sum());
                    statistic.setStatTime(sendTime);
                    resList.add(statistic);
                });
                groupStatisticService.saveBatch(resList);
            }

        }
    }
}
